package postgres

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"manager/errors"
	"manager/model"
	"manager/model/entity"
	"strings"
)

var FirmwaresRecord = &firmwaresRecord{}

type firmwaresRecord struct{}

// Create 创建
func (a *firmwaresRecord) Create(ctx context.Context, m *entity.FirmwaresRecord) (int64, error) {
	err := GetDB(ctx).Create(m).Error
	return m.Id, err
}

// Find 查找详情
func (a *firmwaresRecord) Find(ctx context.Context, in *model.FirmwaresRecordInfoRequest) (*entity.FirmwaresRecord, error) {
	e := &entity.FirmwaresRecord{}

	q := GetDB(ctx).Model(&entity.FirmwaresRecord{})

	if in.Id > 0 {
		err := q.First(&e, in.Id).Error
		return e, err
	}

	count := 0

	if in.FirmwareId != nil {

		q = q.Where("firmware_id = ?", in.FirmwareId)

		count++
	}

	if in.TacticsId != nil {

		q = q.Where("tactics_id = ?", in.TacticsId)

		count++
	}

	if in.Version != nil {

		q = q.Where("version like ?", in.Version)

		count++
	}

	if in.EbikesType != nil {

		q = q.Where("ebikes_type = ?", in.EbikesType)

		count++
	}

	if in.FirmwaresName != nil {

		q = q.Where("firmwares_name like ?", in.FirmwaresName)

		count++
	}

	if count == 0 {
		return e, errors.New("condition illegal")
	}

	err := q.First(&e).Error
	return e, err
}

// Update 更新
func (a *firmwaresRecord) Update(ctx context.Context, id int64, dict map[string]interface{}) error {
	return GetDB(ctx).Model(&entity.FirmwaresRecord{}).Where("id = ?", id).Updates(dict).Error
}

func (a *firmwaresRecord) CheckExistActivePlanByType(typeId []int64) (int64, error) {
	var (
		err error
		id  int64
	)
	t := strings.Replace(strings.Trim(fmt.Sprint(typeId), "[]"), " ", ",", -1)
	sqlStr := "SELECT FT.ID " +
		"FROM FIRMWARES_RECORDS FR JOIN FIRMWARES_TACTICS FT ON FR.TACTICS_ID = FT.ID " +
		"WHERE array [" + t + "]::bigint[] && EBIKES_TYPE " +
		"AND FT.STATUS != 2 limit 1"
	err = db.Raw(sqlStr).Find(&id).Error
	return id, err
}

// Update 更新
func (a *firmwaresRecord) UpdateByTacticsId(ctx context.Context, tacticsId int64, dict map[string]interface{}) error {
	return GetDB(ctx).Model(&entity.FirmwaresRecord{}).Where("tactics_id = ?", tacticsId).Updates(dict).Error
}

// Delete 删除
func (a *firmwaresRecord) Delete(ctx context.Context, id int64) error {
	return GetDB(ctx).Delete(&entity.FirmwaresRecord{}, id).Error
}

// DeleteByTacticsId 删除
func (a *firmwaresRecord) DeleteByTacticsId(ctx context.Context, tacticsId int64) error {
	return GetDB(ctx).Delete(&entity.FirmwaresRecord{}, "tactics_id=?", tacticsId).Error
}

// List 列表查询
func (a *firmwaresRecord) List(ctx context.Context, in *model.FirmwaresRecordListRequest) (int, []*entity.FirmwaresRecord, error) {
	var (
		q                = GetDB(ctx).Model(&entity.FirmwaresRecord{})
		err              error
		total            int64
		firmwaresRecords []*entity.FirmwaresRecord
	)

	if in.FirmwareId != nil {

		q = q.Where("firmware_id = ?", in.FirmwareId)

	}

	if in.TacticsId != nil {

		q = q.Where("tactics_id = ?", in.TacticsId)

	}

	if in.Version != nil {

		q = q.Where("version like ?", in.Version)

	}

	if in.EbikesType != nil {

		q = q.Where("ebikes_type = ?", in.EbikesType)

	}

	if in.FirmwaresName != nil {

		q = q.Where("firmwares_name like ?", in.FirmwaresName)

	}

	if err = q.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	if err = q.Order("created_at desc").Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&firmwaresRecords).Error; err != nil {
		return 0, nil, err
	}
	return int(total), firmwaresRecords, nil
}

// ExecTransaction db事务执行
func (a *firmwaresRecord) ExecTransaction(ctx context.Context, callback func(ctx context.Context) error) error {
	return GetDB(ctx).Transaction(func(tx *gorm.DB) error {
		ctx = context.WithValue(ctx, DBCONTEXTKEY, tx)
		return callback(ctx)
	})
}
